<template>
  <div>
    <el-card>
      <!-- 面包屑 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="UserQuery" class="demo-form-inline" size="large">
        <el-form-item label="昵称">
          <el-input v-model="UserQuery.nickname" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUserListData">搜索</el-button>
          <el-button type="success" @click="dialogVisible = true">新增用户</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 12px">
      <el-table :data="list" style="width: 100%">
        <el-table-column label="用户名" prop="adminname" />
        <el-table-column label="用户昵称" prop="nickname" />
        <el-table-column label="用户头像" prop="avatar">
          <!-- scope固定写法，是一个对象，里面有个属性row,代表着这一行的数据 -->
          <!-- 作用域插槽，能获取值 -->
          <template #default="scope">
            <img :src="scope.row.avatar" style="width: 50px; height: 50px" />
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-switch
              disabled
              :model-value="row.status"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="edit(row)">修改</el-button>
            <el-button type="danger" @click="del(row.adminid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- <el-config-provider :locale="locale"> -->
      <el-pagination
        v-model:current-page="UserQuery.page"
        v-model:page-size="UserQuery.pageSize"
        :page-sizes="[3, 4, 5, 6]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- </el-config-provider> -->
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="mode === 'edit' ? '修改用户' : '新增用户'"
      width="50%"
    >
      <el-form :model="userform" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="adminname" style="width: 85%">
          <el-input v-model="userform.adminname" :disabled="mode === 'edit'" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname" style="width: 85%">
          <el-input v-model="userform.nickname" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userform.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onsubmit"> 确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { UserQuery, User } from '@/types/user'
import { getUserList, addUser, updateUser, deleteUser } from '@/api/user'
import { FormInstance, FormRules, ElMessage, ElMessageBox } from 'element-plus'

const UserQuery = ref<UserQuery>({ page: 1, pageSize: 3, nickname: null })
const list = ref<User[]>([])
const total = ref(0)
const dialogVisible = ref(false)
const userform = ref({
  adminid: '',
  adminname: '',
  nickname: '',
  status: 1
})
const mode = ref('add')
const formRef = ref<FormInstance>()
const getUserListData = async () => {
  const res = await getUserList(UserQuery.value)
  list.value = res.data.data.items
  total.value = res.data.data.total
}
getUserListData()
//每页多少条改变了
const handleSizeChange = (pageSize: number) => {
  UserQuery.value.pageSize = pageSize
  getUserListData()
}
//当前页发生改变
const handleCurrentChange = (page: number) => {
  UserQuery.value.page = page
  getUserListData()
}
const rules = reactive<FormRules>({
  adminname: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }]
})
//增加用户
const onsubmit = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    try {
      if (mode.value === 'add') {
        delete userform.value.adminid
        await addUser(userform.value)
      } else {
        await updateUser(userform.value)
      }
      //关闭Dialog
      dialogVisible.value = false
      //提示成功
      ElMessage.success(mode.value === 'edit' ? '修改成功' : '添加成功')
      //重新获取数据
      if (mode.value === 'add') {
        UserQuery.value.page = 1
      }
      getUserListData()
    } catch (error) {}
  })
}
//修改用户
const edit = (val: User) => {
  dialogVisible.value = true
  mode.value = 'edit'
  userform.value = { ...val }
}
watch(dialogVisible, value => {
  if (!value) {
    //当弹窗关闭时清空
    //把模式设置位置为add
    mode.value = 'add'
    userform.value.adminid = ''
    userform.value.status = 1
    //把表单内容和验证清空
    formRef.value.resetFields()
  }
})
//删除用户
const del = async (val: string) => {
  try {
    await ElMessageBox.confirm('确定删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 发请求
    await deleteUser(val)
    // 提示
    ElMessage.success('删除成功~')
    // 从第一页从新加载
    UserQuery.value.page = 1
    getUserListData()
  } catch (error) {
    console.log(error)
  }
}
</script>

<style scoped lang="less">
.demo-form-inline {
  margin-top: 20px;
}

:deep(.el-pagination) {
  height: 60px;
  line-height: 60px;
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
</style>
